<template>
  <div class="life-management-auth">
    <!-- 背景装饰 -->
    <div class="auth-background">
      <div class="bg-shape shape-1"></div>
      <div class="bg-shape shape-2"></div>
      <div class="bg-shape shape-3"></div>
    </div>

    <!-- 主容器 -->
    <div class="auth-container">
      <!-- 标题区域 -->
      <div class="auth-header">
        <h1 class="auth-title">人生管理系统</h1>
        <p class="auth-desc">知不足而奋进，望远山而前行。</p>

      </div>

      <!-- 表单区域 -->
      <el-card class="auth-form-card">
        <!-- 登录表单 -->
        <el-form
            v-if="activeTab === 'login'"
            :model="loginForm"
            :rules="loginRules"
            ref="loginFormRef"
            label-width="80px"
            @submit.prevent="handleLogin"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                prefix-icon="el-icon-user"
                clearable
            ></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
                v-model="loginForm.password"
                :type="showLoginPassword ? 'text' : 'password'"
                placeholder="请输入密码（6-16位字符）"
                prefix-icon="el-icon-lock"
                clearable
            >
              <i
                  slot="suffix"
                  class="el-icon"
                  :class="showLoginPassword ? 'el-icon-eye' : 'el-icon-eye-close'"
                  @click="showLoginPassword = !showLoginPassword"
                  style="cursor: pointer"
              ></i>
            </el-input>
          </el-form-item>

          <el-form-item class="remember-form-item">
            <el-row :gutter="20">
              <el-col :span="14">
                <el-checkbox v-model="rememberPassword">记住密码（7天内自动登录）</el-checkbox>
              </el-col>
              <el-col :span="10" class="text-right">
                <el-button type="text" @click="handleForgotPassword">忘记密码？</el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item class="submit-form-item">
            <el-button
                type="primary"
                icon="el-icon-arrow-right"
                class="submit-btn"
                @click="submitLoginForm"
            >
              登录系统
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 注册表单 -->
        <el-form
            v-else
            :model="registerForm"
            :rules="registerRules"
            ref="registerFormRef"
            label-width="80px"
            @submit.prevent="handleRegister"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
                v-model="registerForm.username"
                placeholder="请输入用户名"
                prefix-icon="el-icon-user"
                clearable
            ></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
                v-model="registerForm.password"
                :type="showRegisterPassword ? 'text' : 'password'"
                placeholder="请输入密码（6-16位字符）"
                prefix-icon="el-icon-lock"
                clearable
            >
              <i
                  slot="suffix"
                  class="el-icon"
                  :class="showRegisterPassword ? 'el-icon-eye' : 'el-icon-eye-close'"
                  @click="showRegisterPassword = !showRegisterPassword"
                  style="cursor: pointer"
              ></i>
            </el-input>
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
                v-model="registerForm.confirmPassword"
                :type="showRegisterConfirmPwd ? 'text' : 'password'"
                placeholder="请再次输入密码"
                prefix-icon="el-icon-lock"
                clearable
            >
              <i
                  slot="suffix"
                  class="el-icon"
                  :class="showRegisterConfirmPwd ? 'el-icon-eye' : 'el-icon-eye-close'"
                  @click="showRegisterConfirmPwd = !showRegisterConfirmPwd"
                  style="cursor: pointer"
              ></i>
            </el-input>
          </el-form-item>

          <el-form-item class="submit-form-item">
            <el-button
                type="primary"
                icon="el-icon-check"
                class="submit-btn"
                @click="submitRegisterForm"
            >
              注册账号
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 底部提示 -->
      <div class="auth-footer">
        <el-row type="flex" justify="center">
          <el-button
              type="text"
              class="switch-btn"
              @click="switchTab"
          >
            {{ activeTab === 'login' ? '还没有账号？立即注册' : '已有账号？前往登录' }}
          </el-button>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import {Message} from 'element-ui'

export default {
  name: 'LifeManagementAuth',
  data() {
    // 密码强度验证规则
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else if (value.length < 6 || value.length > 16) {
        callback(new Error('密码长度需在6-16位之间'))
      } else if (!/^(?=.*[a-zA-Z])(?=.*\d).{6,16}$/.test(value)) {
        callback(new Error('密码需包含字母和数字'))
      } else {
        callback()
      }
    }

    // 确认密码验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请确认密码'))
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      activeTab: 'login', // 激活的标签页（login/register）
      // 登录表单
      loginForm: {
        username: '',
        password: ''
      },
      // 注册表单
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      },
      // 显示/隐藏密码
      showLoginPassword: false,
      showRegisterPassword: false,
      showRegisterConfirmPwd: false,
      // 记住密码
      rememberPassword: false,
      // 登录表单验证规则
      loginRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 20, message: '用户名长度需在3-20位之间', trigger: 'blur'}
        ],
        password: [
          {required: true, validator: validatePassword, trigger: 'blur'}
        ]
      },
      // 注册表单验证规则
      registerRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 20, message: '用户名长度需在3-20位之间', trigger: 'blur'}
        ],
        password: [
          {required: true, validator: validatePassword, trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, validator: validateConfirmPassword, trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    // 页面加载时检查是否有记住的密码
    this.checkRememberedPassword()
  },
  methods: {
    // 切换标签页
    handleTabChange(tab) {
      this.activeTab = tab.name
      // 重置对应表单
      if (tab.name === 'login') {
        this.$refs.loginFormRef && this.$refs.loginFormRef.resetFields()
      } else {
        this.$refs.registerFormRef && this.$refs.registerFormRef.resetFields()
      }
    },
    // 快速切换标签页
    switchTab() {
      this.activeTab = this.activeTab === 'login' ? 'register' : 'login'
      // 重置对应表单
      if (this.activeTab === 'login') {
        this.$refs.loginFormRef && this.$refs.loginFormRef.resetFields()
      } else {
        this.$refs.registerFormRef && this.$refs.registerFormRef.resetFields()
      }
    },
    // 提交登录表单
    submitLoginForm() {
      this.$refs.loginFormRef.validate((isValid) => {
        if (isValid) {
          this.handleLogin()
        }
      })
    },
    // 提交注册表单
    submitRegisterForm() {
      this.$refs.registerFormRef.validate((isValid) => {
        if (isValid) {
          this.handleRegister()
        }
      })
    },
    // 处理登录逻辑
    handleLogin() {
      // 模拟登录请求（实际项目中替换为真实接口请求）
      console.log('登录请求参数：', this.loginForm)

      // 登录成功后处理记住密码
      if (this.rememberPassword) {
        this.savePassword()
      } else {
        this.clearPassword()
      }
      this.$axios.post('/user/login', this.loginForm).then(res => {
        if (res.data.code === 200) {
          // 登录成功提示与跳转
          Message.success({
            message: '登录成功！正在进入系统...',
            duration: 1500
          })
          setTimeout(() => {
            this.$router.push('/Index') // 跳转到首页/控制台
          }, 1500)
        } else {
          this.$message.error({
            type: 'error',
            message: res.data.message
          })
        }
      }).catch()

    },
    // 处理注册逻辑
    handleRegister() {
      // 模拟注册请求（实际项目中替换为真实接口请求）
      console.log('注册请求参数：', this.registerForm)
      this.$axios.post('/user/register', this.registerForm).then(res => {
        if (res.data.code === 200) {
          // 模拟注册成功提示与切换到登录页
          Message.success({
            message: '注册成功！请登录...',
            duration: 1500
          })
          setTimeout(() => {
            this.activeTab = 'login'
            // 注册成功后自动填充用户名
            this.loginForm.username = this.registerForm.username
            this.registerForm = {
              username: '',
              password: '',
              confirmPassword: ''
            }
            this.$refs.registerFormRef && this.$refs.registerFormRef.resetFields()
          }, 1500)
        } else {
          this.$message.error(res.data.message)
        }
      }).catch()


    },
    // 忘记密码处理
    handleForgotPassword() {
      // 可跳转至密码重置页面或弹出重置模态框
      Message.info('密码重置功能待实现')
    },
    // 保存密码到本地存储
    savePassword() {
      const {username, password} = this.loginForm
      const expireTime = new Date().getTime() + 7 * 24 * 60 * 60 * 1000 // 7天有效期
      localStorage.setItem('rememberedUser', JSON.stringify({
        username,
        password,
        expireTime
      }))
    },
    // 清除本地存储的密码
    clearPassword() {
      localStorage.removeItem('rememberedUser')
    },
    // 检查本地存储的记住密码
    checkRememberedPassword() {
      const rememberedUser = localStorage.getItem('rememberedUser')
      if (rememberedUser) {
        try {
          const {username, password, expireTime} = JSON.parse(rememberedUser)
          const now = new Date().getTime()

          // 检查是否过期
          if (now <= expireTime) {
            this.loginForm.username = username
            this.loginForm.password = password
            this.rememberPassword = true
          } else {
            // 已过期，清除存储
            this.clearPassword()
          }
        } catch (e) {
          console.error('解析记住的密码失败：', e)
          this.clearPassword()
        }
      }
    }
  }
}
</script>

<style scoped>
.life-management-auth {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-color: #f5f7fa;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: "Microsoft YaHei", "Helvetica Neue", Arial, sans-serif;
}

/* 背景装饰 */
.auth-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.bg-shape {
  position: absolute;
  border-radius: 50%;
  background: linear-gradient(135deg, rgba(41, 98, 255, 0.1), rgba(41, 98, 255, 0.05));
}

.shape-1 {
  width: 600px;
  height: 600px;
  top: -200px;
  left: -200px;
}

.shape-2 {
  width: 800px;
  height: 800px;
  bottom: -300px;
  right: -300px;
}

.shape-3 {
  width: 400px;
  height: 400px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0.3;
}

/* 主容器 */
.auth-container {
  position: relative;
  z-index: 1;
  width: 100%;
  max-width: 480px;
  padding: 0 20px;
}

/* 标题区域 */
.auth-header {
  text-align: center;
  margin-bottom: 20px;
}

.auth-title {
  font-size: 28px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 8px;
}

.auth-desc {
  font-size: 14px;
  color: #86909c;
  margin-bottom: 20px;
}

/* Element UI 标签页样式调整 */
.auth-tabs {
  --el-tabs-line-height: 40px;
  --el-tabs-nav-font-size: 16px;
  margin-bottom: 10px;
}

.el-tabs__header {
  margin-bottom: 0 !important;
}

.el-tabs__item {
  color: #86909c !important;
  font-weight: 500;
}

.el-tabs__item.is-active {
  color: #2962ff !important;
}

.el-tabs__active-bar {
  background-color: #2962ff !important;
  height: 3px !important;
  border-radius: 3px;
}

/* 表单卡片样式 */
.auth-form-card {
  border-radius: 12px !important;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08) !important;
  overflow: hidden;
}

.el-card__body {
  padding: 30px !important;
}

/* 表单项样式调整 */
.el-form-item {
  margin-bottom: 20px !important;
}

.el-form-item__label {
  color: #1d2129 !important;
  font-weight: 500 !important;
}

.el-input {
  --el-input-height: 44px !important;
  --el-input-font-size: 14px !important;
  border-radius: 8px !important;
}

.el-input__inner {
  border-radius: 8px !important;
}

.el-input__prefix {
  color: #86909c !important;
}

/* 记住密码项样式 */
.remember-form-item {
  margin-bottom: 24px !important;
}

.el-checkbox__label {
  color: #4e5969 !important;
  font-size: 13px !important;
}

/* 提交按钮样式 */
.submit-form-item {
  margin-bottom: 0 !important;
}

.submit-btn {
  width: 100% !important;
  height: 44px !important;
  font-size: 16px !important;
  border-radius: 8px !important;
  background-color: #2962ff !important;
  border-color: #2962ff !important;
}

.submit-btn:hover {
  background-color: #1d4ed8 !important;
  border-color: #1d4ed8 !important;
}

/* 底部提示样式 */
.auth-footer {
  margin-top: 20px;
}

.switch-btn {
  color: #2962ff !important;
  font-size: 14px !important;
  padding: 0 4px !important;
}

.switch-btn:hover {
  color: #1d4ed8 !important;
  text-decoration: underline;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-card__body {
    padding: 24px !important;
  }

  .auth-title {
    font-size: 24px;
  }

  .submit-btn {
    height: 40px !important;
    font-size: 15px !important;
  }
}

@media (max-width: 480px) {
  .auth-container {
    padding: 0 16px;
  }

  .el-card__body {
    padding: 20px !important;
  }

  .el-form-item {
    margin-bottom: 16px !important;
  }

  .remember-form-item {
    margin-bottom: 20px !important;
  }

  .el-form-item__label {
    font-size: 13px !important;
  }
}
</style>